package com.chenhui.estateback.controller;

import com.chenhui.estateback.entity.User;
import com.chenhui.estateback.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/user")
public class UserHandler {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/all/{page}/{size}")
    public Page<User> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable  pageable= PageRequest.of(page-1,size);
        return  userRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody User user){
        return save_to_database(user);
    }

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") Integer id){
        return userRepository.findById(id).get();
    }

    @PutMapping("/update")
    public  String update(@RequestBody User user){
        return save_to_database(user);
    }

    private String save_to_database(@RequestBody User user) {
        User saved = userRepository.save(user);
        if (saved != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        userRepository.deleteById(id);
    }
}
